# coding=utf-8

# 1. 创建类
# 2. 初始化,文件是否存在
# 3. yaml读取

import os
from string import Template

import yaml



class YamlReader():
    def __init__(self, yaml_p):
        if os.path.exists(yaml_p):
            self.yaml_p = yaml_p
        else:
            raise FileNotFoundError("文件不存在")
        self._data = None
        self._data_all = None

    def data(self):
        # 读取单个文档
        if not self._data:
            with open(self.yaml_p, 'r', encoding='utf-8') as f:
                self._data = yaml.safe_load(f)
        return self._data

    def data_all(self):
        # 读取全部文档
        if not self._data:
            with open(self.yaml_p, 'r', encoding='utf-8') as f:
                self._data_all = list(yaml.safe_load_all(f))
        return self._data_all

    def write(self, *args):
        from config.Conf import _temporary_value_file
        # 写入数据
        data = self.data()
        for key in data.keys():  # 清空上次数据
            if not data[key]:
                data[key] = ''
        # 重新写入数据
        le = len(args)
        a = 0
        for key in data.keys():
            if a <= le-1:
                data[key] = args[a]
                a += 1
        # print(_temporary_value_file)
        with open(_temporary_value_file, "w", encoding="utf-8") as f:
            yaml.dump(data, f)
        return data

    def replace_yaml(self, **kwargs):
        with open(self.yaml_p, encoding="utf-8") as fp:
            yaml_str = fp.read()
            template = Template(yaml_str)
            dic = {}
            for key in kwargs:
                dic[key] = kwargs[key]
                ss = template.safe_substitute(dic)
            print(ss)

            student = yaml.full_load(ss)
            print('student', type(student))
            # print(student)
if __name__ == "__main__":
    # a()
    ym = YamlReader('a.yml')
    ym.replace_yaml(age='777')